package lwk.juc.queue;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author:lwk
 * @create: 2022-08-18 20:15
 * @Description: 同步队列
 *
 * 和其他的BlockingQueue不同，SynchronousQueue不存储元素
 * put了一个元素，必须先从里面take取出来，否则不能在put进去值
 */
public class SynchronousQueueDemo {

    public static void main(String[] args) {
        SynchronousQueue<Object> synchronousQueue = new SynchronousQueue<>();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "put A");
                synchronousQueue.put("A");
                TimeUnit.SECONDS.sleep(1);

                System.out.println(Thread.currentThread().getName() + "put B");
                synchronousQueue.put("B");
                TimeUnit.SECONDS.sleep(1);

                System.out.println(Thread.currentThread().getName() + "put C");
                synchronousQueue.put("C");
                TimeUnit.SECONDS.sleep(1);

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"T1").start();


        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "===>" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(1);

                System.out.println(Thread.currentThread().getName() + "===>" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(1);

                System.out.println(Thread.currentThread().getName() + "===>" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(1);

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"T2").start();

    }
}
